package startup.security.service.impl;

import com.amazonaws.services.s3.model.CannedAccessControlList;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import startup.security.config.AmazonS3Manager;
import startup.security.config.S3Config;
import startup.security.service.FileService;
import java.io.File;
import java.util.UUID;

/**
 * @author ly
 * @date 2023/03/01
 *
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private S3Config s3Config;


    /**
     * 上传文件
     *
     * @param uploadPath
     * @param uploadFile
     * @return
     */
    @Override
    public String upload(String uploadPath, File uploadFile) {
        String filePathName = getFilePath(s3Config.getDirectory() + uploadPath, uploadFile);
        AmazonS3Manager.uploadToS3(s3Config.getBucketName(), uploadFile, filePathName, CannedAccessControlList.PublicReadWrite);
        return filePathName;
    }

    /**
     * 获取临时 URL
     *
     * @param pathUrl 包存储的路径，形如 xxxx/xxx/xx/x.zip
     * @return
     */
    @Override
    public String getUrl(String pathUrl) {
        String url = AmazonS3Manager.getUrlToS3(s3Config.getBucketName(), pathUrl);
        return url;
    }


    /**
     * @param path
     * @param file
     * @desc 生成路径以及文件名
     */
    @Override
    public String getFilePath(String path, File file) {
        /**获取文件后缀名**/
        String suffix = file.getName().substring(file.getName().lastIndexOf("."));
        /**上传的文件名称重命名**/
        String fileName = path + UUID.randomUUID() + "/" + file.getName();
        return fileName;
    }

}

